#coding=utf-8
#
# Copyright (C) 2014  NianNian TECH Co., Ltd. All rights reserved.
# Created on Sep 24, 2014, by Junn
#
import time
from core.push import push_to_single
import threading
from messages.models import PushMessage
from utils import logs
from celery import  task
from families.models import FamilyShip
import settings

'''
 exec:    
     python manage.py celery worker -B  -S djcelery.schedulers.DatabaseScheduler -l info
'''

lock = threading.Lock()  


class CountUnreadPostsThread(threading.Thread):
    def __init__(self, *args, **kwargs):
        threading.Thread.__init__(self, *args, **kwargs)

    def run(self):
        count_unread_posts()
        
            
def count_unread_posts():
    logs.debug('===============================> Reading new posts count ... \n')
    fships = FamilyShip.objects.filter(unread_count__gt=0)   # TODO: put this into families module...
    if not fships: return
    unread_list = _get_unread_dict(fships)
    for k in unread_list:
        # this 'delay' not error, just add job into work_queue
        push_to_single.delay(k, PushMessage('P', u'unread_posts_count', extras={'upcs': unread_list[k]})) 
        
    #lock.acquire()
    #logs.debug('===============================> fships.update() ... \n')
    #fships.update(unread_count=0)
    #lock.release()
  
def _get_unread_dict(fships):
    '''将many2many结构数据, 汇集成以用户id为key的dict数据结构返回, 用户在某家庭内的未读动态数
    
    return:
        {u1: [{'fid':2, 'unc':3}, {'fid':4, 'unc':5}], u2: [{'fid':1, 'unc':3}, ], ...}, 
    '''
    udict = {}
    for fs in fships:
        if not fs.member_id in udict.keys():
            udict[fs.member_id]= []
        udict[fs.member_id].append({'fid': fs.family_id,'unc': fs.unread_count})
            
    return udict          
        


class CountUnreadPostsThreadManager(threading.Thread):
    """This thread is used to count unread posts, 每隔指定时间读取DB中新的动态数
        可使用该自定义线程, 或者用celery定时任务
    
    """
    def __init__(self, *args, **kwargs):
        threading.Thread.__init__(self, *args, **kwargs)

    def run(self):
        logs.info('==================================> CountUnreadPostsThreadManager started...')
        
        self.started = True
        while self.started:
            time.sleep(settings.CUPT_SLEEP_INTERVAL)
            CountUnreadPostsThread().start()
       
        logs.info('==================================> CountUnreadPostsThreadManager stoped...')     
            
    def stop(self):
        self.started = False  
        
    def is_started(self):
        return self.started                  


## sample for testing 
# @task
# def add(x, y):
#     time.sleep(10)
#     return x + y   
# 
# @task
# def host():
#     time.sleep(2)
#     print subprocess.check_output(['hostname'])

